import React, { useState } from 'react'
import type { FC } from 'react'
import { Space, Table, Button, Divider } from 'antd'
import type { TableProps } from 'antd'
import type { SetURLSearchParams } from 'react-router-dom'
import { useRoleIdToUserList } from '@/hooks/useRole'

interface IProps {
  total: number
  data: IRoleType.IRole[]
  loadData: (page: number) => void
  page: number
  setPageNum: (pageNum: number) => void
  setSearch: SetURLSearchParams
  setRoleHandle: (item: IRoleType.IRole) => void
}

const DataTable: FC<IProps> = ({
  total,
  data,
  loadData,
  page,
  setPageNum,
  setSearch,
  setRoleHandle
}) => {
  const [loading, setLoading] = useState(false)
  const [users, setUsers] = useState<Record<number, IUserType.IUserItem[]>>({})
  // 角色对应用户列表信息
  const loadUsers = useRoleIdToUserList()

  // 页码改变获取下一页数据
  const onChange = (page: number) => {
    loadData(page)
    setSearch({ page: String(page) })
    setPageNum(page)
  }

  const columns: TableProps<IRoleType.IRole>['columns'] = [
    {
      title: '编号',
      dataIndex: 'id',
      width: 60
    },
    {
      title: '角色名称',
      dataIndex: 'name'
    },
    {
      title: '操作',
      render: (_, record) => {
        return (
          <Space size="middle">
            <Button
              size="small"
              type="primary"
              onClick={() => {
                // console.log('调用父传入过来的方法', record.id, record.name)
                setRoleHandle(record)
              }}
            >
              修改
            </Button>
            <Button size="small" type="primary" danger>
              删除
            </Button>
          </Space>
        )
      }
    }
  ]

  return (
    <Table
      loading={loading}
      rowKey={(record) => record.id}
      expandable={{
        expandedRowRender: (record) => (
          <div>
            {users[record.id] ? (
              users[record.id].map((item) => (
                <h3 key={item.id}>{item.realname}</h3>
              ))
            ) : (
              <h3>加载中...</h3>
            )}
          </div>
        ),
        rowExpandable: (record) => true,
        onExpand: async (isExpand, record) => {
          if (isExpand) {
            setLoading(true)
            let ret = await loadUsers(record.id, 1)
            setUsers((v) => ({
              ...v,
              [record.id]: ret.users
            }))
            setLoading(false)
          }
        }
      }}
      columns={columns}
      dataSource={data}
      pagination={{
        position: ['bottomLeft'],
        current: page,
        total,
        onChange
      }}
    />
  )
}

export default DataTable
